package com.example.demo.zaqizabatest.leetcode.day6;

/**
 * 从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
public class Solution3 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }

        List<List<Integer>> tree = new ArrayList<>();
        List<Integer> rootNode = new ArrayList<>();
        rootNode.add(root.val);
        tree.add(rootNode);
        if (root.left != null && root.right != null){
            traversal(tree, false, root.left, root.right);
        } else if (root.left == null && root.right != null){
            traversal(tree, false, root.right);
        } else if (root.left != null && root.right == null){
            traversal(tree, false, root.left);
        }

        return tree;
    }

    private void traversal(List<List<Integer>> tree, boolean sort, TreeNode... subNodes) {
        List<Integer> subNodeVals = new ArrayList<>();
        List<TreeNode> subSubNodes = new ArrayList<>();
        if (subNodes.length != 0){
            for (TreeNode subNode : subNodes){
                subNodeVals.add(subNode.val);
                if (subNode.left != null) {
                    subSubNodes.add(subNode.left);
                }
                if (subNode.right != null) {
                    subSubNodes.add(subNode.right);
                }
            }
            if (!sort){
                Collections.reverse(subNodeVals);
            }
            tree.add(subNodeVals);
            traversal(tree, !sort, subSubNodes.toArray(new TreeNode[subSubNodes.size()]));
        }
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }



}
